//
//  XiaoximenTimePlaceVoteViewController.m
//  Xiaoximen_iOS
//
//  Created by Wang Zhongyu on 12-7-19.
//  Copyright (c) 2012年 Peking University. All rights reserved.
//

#import "XiaoximenTimePlaceVoteViewController.h"
#import "ASIHTTPRequest.h"
#import "XiaoximenAppDelegate.h"
#import "SBJson.h"

@interface XiaoximenTimePlaceVoteViewController () {
	ASIHTTPRequest *requestPlace;
	ASIHTTPRequest *requestTime;
	BOOL bRequest;
}

@end

@implementation XiaoximenTimePlaceVoteViewController
@synthesize placeTableView;
@synthesize timeTableView;
@synthesize canVote;
@synthesize party;
@synthesize person;
@synthesize placeImages;
@synthesize timeImages;
@synthesize placeYess;
@synthesize timeYess;
@synthesize delegate;
@synthesize progressHub;

- (NSObject<PABezelHUDDelegate> *)delegate {
    if (delegate == nil) {
        delegate = (NSObject<PABezelHUDDelegate> *)[UIApplication sharedApplication].delegate;
    }
    return delegate;
}
- (MBProgressHUD *)progressHub{
    if (progressHub == nil) {
        progressHub = self.delegate.progressHub;
    }
    return progressHub;
}
- (void)showProgressHubWithTitle:(NSString *)title{
    self.progressHub.mode = MBProgressHUDModeIndeterminate;
    self.progressHub.delegate = nil;
    self.progressHub.labelText = title;
    [self.progressHub show:YES];
}
- (void)changeProgressHub:(NSString *)title
{
	progressHub.animationType = MBProgressHUDAnimationZoom;
    self.progressHub.labelText = title;
    self.progressHub.mode = MBProgressHUDModeCustomView;
    [self.progressHub hide:YES afterDelay:1];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	placeImages = [[NSMutableArray alloc] init];
	
	if (canVote) {
		self.navigationItem.rightBarButtonItem =
		[[UIBarButtonItem alloc] initWithTitle:@"继续"
										  style:UIBarButtonItemStyleBordered
										 target:self
										 action:@selector(onVote:)];
	}
	
	for (int i = 0; i < party.places.count; i++) {
		UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 43)];
		imageView.image = [UIImage imageNamed:@"text"];
		[placeImages addObject:imageView];
	}
	
	timeImages = [[NSMutableArray alloc] init];
	for (int i = 0; i < party.timeIntervals.count; i++) {
		UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 43)];
		imageView.image = [UIImage imageNamed:@"text"];
		[timeImages addObject:imageView];
	}
	
	placeYess = [[NSMutableArray alloc] init];
	for (int i = 0; i < party.places.count; i++) {
		UIImageView *yes = [[UIImageView alloc] initWithFrame:CGRectMake(200, 12, 20, 20)];
		yes.image = [UIImage imageNamed:@"y"];
		[placeYess addObject:yes];
	}
	
	timeYess = [[NSMutableArray alloc] init];
	for (int i = 0; i < party.timeIntervals.count; i++) {
		UIImageView *yes = [[UIImageView alloc] initWithFrame:CGRectMake(200, 12, 20, 20)];
		yes.image = [UIImage imageNamed:@"y"];
		[timeYess addObject:yes];
	}
	
	bRequest = NO;
	
}

- (void)viewDidUnload
{
    [self setPlaceTableView:nil];
    [self setTimeTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if ([tableView isEqual:placeTableView]) return party.places.count;
	else return party.timeIntervals.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell;
	if ([tableView isEqual:placeTableView]) {
		static NSString *CellIdentifier = @"placeIdentifier";
		cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
		if ([[person.placeVotes valueForKey:[NSString stringWithFormat:@"%d", [[party.places objectAtIndex:indexPath.row] ID]]] isEqualToString:@"YES"]) {
			UIImageView * imageView = [placeImages objectAtIndex:indexPath.row];
			imageView.image = [UIImage imageNamed:@"textfield"];
		}
		[cell addSubview:[placeImages objectAtIndex:indexPath.row]];
		if ([[person.placeVotes valueForKey:[NSString stringWithFormat:@"%d", [[party.places objectAtIndex:indexPath.row] ID]]] isEqualToString:@"YES"]) [cell addSubview:[placeYess objectAtIndex:indexPath.row]];
	
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 9, 140, 25)];
		label.text = [[party.places objectAtIndex:indexPath.row] placeName];
		label.font = [UIFont boldSystemFontOfSize:17];
		label.numberOfLines = 0;
		label.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.0];
		[cell addSubview:label];
	} else {
		static NSString *CellIdentifier = @"timeIdentifier";
		cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		
		if ([[person.timeVotes valueForKey:[NSString stringWithFormat:@"%d", [[party.timeIntervals objectAtIndex:indexPath.row] ID]]] isEqualToString:@"YES"]) {
			UIImageView * imageView = [timeImages objectAtIndex:indexPath.row];
			imageView.image = [UIImage imageNamed:@"textfield"];
		}
		[cell addSubview:[timeImages objectAtIndex:indexPath.row]];
		if ([[person.timeVotes valueForKey:[NSString stringWithFormat:@"%d", [[party.timeIntervals objectAtIndex:indexPath.row] ID]]] isEqualToString:@"YES"]) [cell addSubview:[timeYess objectAtIndex:indexPath.row]];
		
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 6, 180, 15)];
		label.text = [[party.timeIntervals objectAtIndex:indexPath.row] displayDay];
		label.font = [UIFont boldSystemFontOfSize:15];
		label.numberOfLines = 0;
		label.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.0];
		[cell addSubview:label];

		UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 21, 180, 15)];
		label2.text = [[party.timeIntervals objectAtIndex:indexPath.row] displayTimeInterval];
		label2.font = [UIFont boldSystemFontOfSize:15];
		label2.numberOfLines = 0;
		label2.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.0];
		[cell addSubview:label2];
	}
	
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)onVote:(id)sender
{	
	if (bRequest) return ;
	bRequest = YES;
	
	if ([party.title isEqualToString:@"学习包粽子(Demo)"]) {
		[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
		return ;
	}
	
	
	[self showProgressHubWithTitle:@"投票中...先别点哦^_^"];
	NSMutableArray *reply_place = [[NSMutableArray alloc] initWithCapacity:party.places.count];
	for (int i = 0; i < party.places.count; i++) {
		NSMutableDictionary *place_dict = [[NSMutableDictionary alloc] init];
		[place_dict setObject:[NSNumber numberWithInt:[[party.places objectAtIndex:i] ID]] forKey:@"option_id"];
		UITableViewCell *cell = [self.placeTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
		if ([[[placeYess objectAtIndex:i] superview] isEqual:cell]) {
			[place_dict setObject:[NSNumber numberWithInt:1] forKey:@"checked"];
		} else {
			[place_dict setObject:[NSNumber numberWithInt:0] forKey:@"checked"];
		}
		[reply_place addObject:place_dict];
	}
	
	int invitation_id = party.ID;
	int user_id = [[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"] intValue];
	NSString *result = [reply_place JSONRepresentation];
	NSLog(@"result:%@", result);
	
	NSString *urlString = [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/reply/place?user_id=%d&result=%@", invitation_id, user_id, result];
	
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSLog(@"%@", urlString);
	NSURL *urlPlace = [NSURL URLWithString:urlString];
	requestPlace = [ASIHTTPRequest requestWithURL:urlPlace];
	[requestPlace setDelegate:self];
	[requestPlace startAsynchronous];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
	if (!canVote) return ;
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	if ([tableView isEqual:placeTableView]) {
		if ([[[placeYess objectAtIndex:indexPath.row] superview] isEqual:cell]) {
			[[placeYess objectAtIndex:indexPath.row] removeFromSuperview];
			UIImageView *image = [placeImages objectAtIndex:indexPath.row];
			image.image = [UIImage imageNamed:@"text"];
		} else {
			[cell addSubview:[placeYess objectAtIndex:indexPath.row]];
			UIImageView *image = [placeImages objectAtIndex:indexPath.row];
			image.image = [UIImage imageNamed:@"textfield"];
		}
	} else {
		if ([[[timeYess objectAtIndex:indexPath.row] superview] isEqual:cell]) {
			[[timeYess objectAtIndex:indexPath.row] removeFromSuperview];
			UIImageView *image = [timeImages objectAtIndex:indexPath.row];
			image.image = [UIImage imageNamed:@"text"];
		} else {
			[cell addSubview:[timeYess objectAtIndex:indexPath.row]];
			UIImageView *image = [timeImages objectAtIndex:indexPath.row];
			image.image = [UIImage imageNamed:@"textfield"];
		}
	}
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];
	id res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:nil];
	NSLog(@"%@", res);
	if ([request isEqual:requestPlace]) {
		
		NSMutableArray *reply_time = [[NSMutableArray alloc] initWithCapacity:party.timeIntervals.count];
		for (int i = 0; i < party.timeIntervals.count; i++) {
			NSMutableDictionary *time_dict = [[NSMutableDictionary alloc] init];
			[time_dict setObject:[NSNumber numberWithInt:[[party.timeIntervals objectAtIndex:i] ID]] forKey:@"option_id"];
			UITableViewCell *cell = [self.timeTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
			if ([[[timeYess objectAtIndex:i] superview] isEqual:cell]) {
				[time_dict setObject:[NSNumber numberWithInt:1] forKey:@"checked"];
			} else {
				[time_dict setObject:[NSNumber numberWithInt:0] forKey:@"checked"];
			}
			[reply_time addObject:time_dict];
		}
		
		int invitation_id = party.ID;
		int user_id = [[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"] intValue];
		NSString *result = [reply_time JSONRepresentation];
		NSLog(@"result:%@", result);
		
		NSString *urlString = [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/reply/time?user_id=%d&result=%@", invitation_id, user_id, result];
		
		urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		NSLog(@"%@", urlString);
		NSURL *urlTime = [NSURL URLWithString:urlString];
		requestTime = [ASIHTTPRequest requestWithURL:urlTime];
		[requestTime setDelegate:self];
		[requestTime startAsynchronous];
	} else {
		bRequest = NO;
		[self changeProgressHub:@"投票发送成功！"];
		
		NSMutableDictionary *invitationsDownloaded = [[[NSUserDefaults standardUserDefaults] valueForKey:kINVITATIONIDDOWNLOADED] mutableCopy];
		[invitationsDownloaded setObject:@"NO" forKey:[NSString stringWithFormat:@"%d", party.ID]];
		[[NSUserDefaults standardUserDefaults] setObject:invitationsDownloaded forKey:kINVITATIONIDDOWNLOADED];
		
		[self performSegueWithIdentifier:@"CompleteVoteSegue" sender:self];
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSError *error = [request error];
	NSLog(@"%@", error);
	bRequest = NO;
	[self changeProgressHub:@"投票发送失败><"];
	[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
}
@end
